package com.sxhalo.fsms.controller.api;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sxhalo.fsms.exception.BaseEnumError;
import com.sxhalo.fsms.export.ExcelUtils;
import com.sxhalo.fsms.export.ExportSetInfo;
import com.sxhalo.fsms.log.SysControllerLog;
import com.sxhalo.fsms.service.IDeviceAlarmRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sxhalo.fsms.controller.BaseController;
import com.sxhalo.fsms.domain.UserInfo;
import com.sxhalo.fsms.service.IUserInfoService;
import com.sxhalo.fsms.util.ApiResult;
import com.sxhalo.fsms.util.MD5Util;
import com.sxhalo.fsms.util.TokenUtil;
import com.sxhalo.fsms.util.CookieUtils;

@Controller
@RequestMapping("/api")
public class SysUserController extends BaseController {

	@Autowired
	private IUserInfoService userService;
	@Autowired
	private IDeviceAlarmRecordService iAlarmRecordService;




	@ResponseBody
	@SysControllerLog(operationName = "退出", modelName = "用户管理")
	@RequestMapping(value = "/logout", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public ApiResult logout(HttpServletRequest req, HttpServletResponse res) {
		CookieUtils.clearCookie(req, res);
		return ApiResult.retOK(req);
	}

	@ResponseBody
	@SysControllerLog(operationName = "登录", modelName = "用户管理")
	@RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public ApiResult login(String userName, String password, Integer role, HttpServletRequest req,
			HttpServletResponse res) {
		Map<String, Object> bady = new HashMap<>();
		if(userName.equals("admin")){
			role=1;
		}
		bady.put("type", role); // 符合前端规则
		UserInfo record = userService.selectByUserName(userName);
		if (record != null) {
			if (record.getDisable() == 1) {
				bady.put("status", "error");
				bady.put("errorMsg", "此用户已被禁用！");
				return ApiResult.retOK(req, bady);
			}
			if (MD5Util.MD5Encode(password).equals(record.getPassword())) {
				if(role.equals(record.getRoleId())) {
					bady.put("status", "ok");
					String authority[] = { "admin", "guest" };
					bady.put("currentAuthority", authority);
					String token = TokenUtil.createToken(record.getUserId(), record.getRoleId());
					CookieUtils.setCookie(res, "token", token);
					// 登陆成功 查询设备维保过期的设备存入报警表
					iAlarmRecordService.maintenanceIntervalAram();
					return ApiResult.retOK(req, bady);
				} else {
					bady.put("status", "error");
					bady.put("errorMsg", "用户角色选择错误！");
					return ApiResult.retOK(req, bady);
				}
			} else {
				bady.put("status", "error");
				bady.put("errorMsg", "用户名或密码错误");
				return ApiResult.retOK(req, bady);
			}
		} else {
			bady.put("status", "error");
			bady.put("errorMsg", "用户名或密码错误");
			return ApiResult.retOK(req, bady);
		}
	}

	@ResponseBody
	@RequestMapping(value = "/currentUser", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public ApiResult currentUser(HttpServletRequest req) {
		String token = CookieUtils.getCookieValue(req, "token");
		if (token != null) {
			Integer userId = TokenUtil.getUserId(token);
			UserInfo record = userService.selectByPrimaryKey(userId);
			Map<String, Object> bady = new HashMap<>();
			bady.put("userName", record.getUserName());
			bady.put("userId", record.getUserId());
			bady.put("role", record.getRoleId());

			String url2 =  req.getServerName()// 服务器地址
					+ ":" + req.getLocalPort();// 端口
			bady.put("serviceUrl",url2);
			//bady.put("serviceUrl","172.16.99.188:8080");
			return ApiResult.retOK(req, bady);
		} else {
			return ApiResult.retFail("401", "请登录");
		}
	}

	@ResponseBody
	@RequestMapping(value = "/user/countByRole", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public ApiResult countByRole(Integer roleId,HttpServletRequest req) {
		int count=userService.getCount(" role_id= "+roleId + " and  delete_flag=0");
			return ApiResult.retOK(req, count);
	}

	@ResponseBody
	@RequestMapping(value = "/user", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public ApiResult findUser(Integer current, Integer pageSize, HttpServletRequest req) {
		String where = getWhere(req);
		String order = "";
		if (!isBlank(req.getParameter("userName"))) {
			where += " and user_name like '%" + req.getParameter("userName").trim() + "%'";
		}
		if (!isBlank(req.getParameter("realName"))) {
			where += " and real_name like '%" + req.getParameter("realName").trim() + "%'";
		}
		if (!isBlank(req.getParameter("sex"))) {
			where += " and sex = " + req.getParameter("sex").trim();
		}
		if (!isBlank(req.getParameter("roleName"))) {
			where += " and role_id = " + req.getParameter("roleName").trim();
		}
		if (!isBlank(req.getParameter("departmentName"))) {
			where += " and department_id = " + req.getParameter("departmentName").trim();
		}

		if (!isBlank(req.getParameter("post"))) {
			where += " and post like '%" + req.getParameter("post").trim() + "%'";
		}
		if (!isBlank(req.getParameter("title"))) {
			where += " and title like '%" + req.getParameter("title").trim() + "%'";
		}
		if (!isBlank(req.getParameter("phoneNumber"))) {
			where += " and phone_number like '%" + req.getParameter("phoneNumber").trim() + "%'";
		}
		String token = CookieUtils.getCookieValue(req, "token");

		if (token != null) {
			Integer roleId = TokenUtil.getRoleId(token);
			if(roleId!=1){
				where+=" and role_id>= " +roleId;
			}
		}

		return findList(current, pageSize, where, order, userService);
	}

	@ResponseBody
	@SysControllerLog(operationName = "新增用户", modelName = "用户管理")
	@RequestMapping(value = "/user", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public ApiResult saveUser(@RequestBody UserInfo record, HttpServletRequest req) {
		Timestamp nowtime = new Timestamp(System.currentTimeMillis());
		record.setUserId(userService.getMaxId() + 1);
		record.setPassword(MD5Util.MD5Encode("111111"));
		record.setDeleteFlag(0);
		record.setUpdateTime(nowtime);
		record.setCreateTime(nowtime);
		userService.insertSelective(record);
		return ApiResult.retOK(req);
	}

	@ResponseBody
	@RequestMapping(value = "/user/validPassWord", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public ApiResult validCode(Integer userId, String password, HttpServletRequest req) {
		UserInfo record = userService.selectByPrimaryKey(userId);
		String psd = MD5Util.MD5Encode(password);
		if (psd.equals(record.getPassword())) {
			return ApiResult.retOK(req);
		}
		return ApiResult.retOK(req, BaseEnumError.密码错误);
	}

	@ResponseBody
	@SysControllerLog(operationName = "重置密码/更新密码", modelName = "用户管理")
	@RequestMapping(value = "/user/updatePassword", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
	public ApiResult resetPassword(Integer userId, String password, HttpServletRequest req) {
		UserInfo record = new UserInfo();
		Timestamp nowtime = new Timestamp(System.currentTimeMillis());
		record.setUserId(userId);
		record.setPassword(MD5Util.MD5Encode(password == null ? "111111" : password));
		record.setUpdateTime(nowtime);
		userService.updateByPrimaryKeySelective(record);
		return ApiResult.retOK(req);
	}

	@ResponseBody
	@SysControllerLog(operationName = "更新用户", modelName = "用户管理")
	@RequestMapping(value = "/user", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
	public ApiResult updateUser(@RequestBody UserInfo record, HttpServletRequest req) {
		Timestamp nowtime = new Timestamp(System.currentTimeMillis());
		record.setUpdateTime(nowtime);
		userService.updateByPrimaryKeySelective(record);
		return ApiResult.retOK(req);
	}

	@ResponseBody
	@SysControllerLog(operationName = "删除用户", modelName = "用户管理")
	@RequestMapping(value = "/user", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
	public ApiResult delUser(Integer userId, HttpServletRequest req) {
		userService.deleteByPrimaryKey(userId);
		return ApiResult.retOK(req);
	}

	@ResponseBody
	@SysControllerLog(operationName = "批量删除", modelName = "用户管理")
	@RequestMapping(value = "/user/batchdel", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
	public ApiResult batchUser(String ids, String method, HttpServletRequest req) {
		userService.deleteByWhere(" user_id in (" + ids + ")");
		return ApiResult.retOK(req);
	}
	
	@ResponseBody
	@RequestMapping(value = "/validUserName", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public ApiResult validCode(String userName, HttpServletRequest req) {
		UserInfo record = userService.selectByUserName(userName);
		if (record == null) {
			return ApiResult.retOK(req);
		}
		return ApiResult.retFail(BaseEnumError.用户名不可用);
	}

	// 表头选择
	private List<String[]> createUsersExcelHead() {
		List<String[]> headlist = new ArrayList<String[]>();
		String[] row1 = { "用户id", "用户名", "真实姓名", "性别", "角色", "部门", "职务", "职称", "电话", "入职时间" };
		headlist.add(row1);
		return headlist;
	}

	@ResponseBody
	@RequestMapping(value = "/exportUserExcel", method = RequestMethod.GET)
	public void userDownload(String keyword, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		String fileName = "用户列表";
		String[] Userkeys = { "userId", "userName", "realName", "sex", "roleName", "departmentName", "post", "title",
				"phoneNumber", "entryTime", };

		String where = getWhere(request);
		List<UserInfo> data = userService.findPagerList(0, -1, where, "");

		ExportSetInfo info = new ExportSetInfo();
		List<Map<String, Object>> coalSalesList = createUserListRecord(data);
		info.setHeadNames(createUsersExcelHead());
		info.setDatalist(coalSalesList);
		info.setTitles(fileName);
		info.setFieldNames(Userkeys);
		info.setOut(os);
		ExcelUtils.export2Excel(info);
		ExcelUtils.ExcelDownload(fileName, response, os);

	}

	private List<Map<String, Object>> createUserListRecord(List<UserInfo> data) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		for (UserInfo fd : data) {
			Map<String, Object> mapValue = new HashMap<String, Object>();
			mapValue.put("userId", fd.getUserId());
			mapValue.put("userName", fd.getUserName());
			mapValue.put("realName", fd.getRealName());
			mapValue.put("sex", fd.getSex() == 1 ? "男" : "女");
			mapValue.put("roleName", fd.getRoleName());
			mapValue.put("departmentName", fd.getDepartmentName());
			mapValue.put("post", fd.getPost());
			mapValue.put("title", fd.getTitle());
			mapValue.put("phoneNumber", fd.getPhoneNumber());
			mapValue.put("entryTime", fd.getEntryTime() == null ? "" : dateFormat.format(fd.getEntryTime()));
			// mapValue.put("updateTime", dateFormat.format(fd.getUpdateTime()));
			listmap.add(mapValue);
		}

		return listmap;
	}

	private String getWhere(HttpServletRequest req) {
		String where = "delete_flag=0";

		if (!isBlank(req.getParameter("userName"))) {
			where += " and user_name like '%" + req.getParameter("userName").trim() + "%'";
		}
		if (!isBlank(req.getParameter("realName"))) {
			where += " and real_name like '%" + req.getParameter("realName").trim() + "%'";
		}
		if (!isBlank(req.getParameter("sex"))) {
			where += " and sex = " + req.getParameter("sex").trim();
		}
		if (!isBlank(req.getParameter("roleName"))) {
			where += " and role_id = " + req.getParameter("roleName").trim();
		}
		if (!isBlank(req.getParameter("departmentName"))) {
			where += " and department_id = " + req.getParameter("departmentName").trim();
		}

		if (!isBlank(req.getParameter("post"))) {
			where += " and post like '%" + req.getParameter("post").trim() + "%'";
		}
		if (!isBlank(req.getParameter("title"))) {
			where += " and title like '%" + req.getParameter("title").trim() + "%'";
		}
		if (!isBlank(req.getParameter("phoneNumber"))) {
			where += " and phone_number like '%" + req.getParameter("phoneNumber").trim() + "%'";
		}
		return where;
	}

}
